package com.lh.center.common.web.advice;

import cn.hutool.core.collection.CollectionUtil;
import com.lh.center.common.exception.CommonException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.multipart.MultipartFile;

import java.util.Set;

/**
 * 上传excel检查切面
 */
@Aspect
public class ExcelUploadAspect {

    public static final Set<String> EXCEL_SUFFIX = CollectionUtil.newHashSet("xls","xlsx","XLS","XLSX");

    @Pointcut("@annotation(com.lh.center.common.annotations.ExcelUpload)")
    public void execute() {}

    @Before("execute()")
    public void doBefore(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        MultipartFile file = (MultipartFile)args[0];
        if (file.isEmpty()) throw new CommonException("excel文件不能为空");
        String fileName = file.getOriginalFilename();
        int index = fileName.lastIndexOf(".");
        if(index < 0) throw new CommonException("文件名缺少后缀");
        String fileType = fileName.substring(index + 1);
        if (!EXCEL_SUFFIX.contains(fileType)) {
            throw new CommonException("当前文件不是excel文件，请上传excel文件");
        }
    }
}
